﻿/*****************************************介绍*****************************************
 * 作者：User
 * 创建时间：2025-04-23 17:33:21
 * 功能：内购SDK管理
**************************************************************************************/

using Game.Framework;
using System.Collections.Generic;
using Unity.Services.Core;
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Extension;

public class IAP : Purchase, IDetailedStoreListener
{
    private IStoreController m_Controller;
    private IExtensionProvider m_Extensions;

    protected override async void Start()
    {
        base.Start();

        // 初始化Unity服务
        await UnityServices.InitializeAsync();

        // 初始化IAP
        var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());

        // 添加产品
        for (int i = 0; i < m_Cfg.products.Length; i++)
        {
            if (m_Cfg.products[i].amount > 0)
                builder.AddProduct(m_Cfg.products[i].id, m_Cfg.products[i].type);
        }

        UnityPurchasing.Initialize(this, builder);
    }

    #region 回调函数，由SDK调用

    public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
    {
        LogManager.Log($"购买失败：{product.appleOriginalTransactionID} {product.transactionID} {failureDescription.productId}", "Purchase", "OnPurchaseFailed");
        // 关闭Loading
        //UIUtility.HidePanel(Game.UI.IAPLoadingPanel.IAPLoadingPanelView.PANEL_KEY);
        EventCenter.Instance.Trigger(GameEventName.BUY_FAILED, product.definition.id);
        UIUtility.ShowToast(BaseDataMgr.Instance.GetLanguageValue("purchase failed!"));
        ResetData();
    }

    /// <summary>
    /// 当Unity IAP遇到不可恢复的初始化错误时调用。
    /// <para>注意，如果网络不可用，这个函数将不会被调用；统一IAP</para>
    /// <para>将尝试初始化，直到可用为止。</para>
    public void OnInitializeFailed(InitializationFailureReason error)
    {
        LogManager.LogWarning($"初始化失败!! error:{error}", "Purchase", "OnInitializeFailed");
    }

    /// <summary>
    /// 当Unity IAP遇到不可恢复的初始化错误时调用。
    /// <para>注意，如果网络不可用，这个函数将不会被调用；统一IAP</para>
    /// <para>将尝试初始化，直到可用为止。</para>
    public void OnInitializeFailed(InitializationFailureReason error, string message)
    {
        LogManager.LogWarning($"初始化失败!! error:{error} msg:{message}", "Purchase", "OnInitializeFailed");
    }

    /// <summary>购买完成时调用，只能在初始化之后使用</summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent)
    {
        string id = purchaseEvent.purchasedProduct.definition.id;
        var product = m_Cfg[id];

        // 如果产品不存在或者已经购买了非消耗型道具，则不进行处理
        if (product == null || GameDataMgr.Instance.IsPurchaseItem(id)) return PurchaseProcessingResult.Complete;

        if (product.type == ProductType.NonConsumable)
            GameDataMgr.Instance.AddPurchasedNonConsumableItem(id);
        // 处理奖励
        new ProductRewardHandler(product);
        UIUtility.ShowToast(BaseDataMgr.Instance.GetLanguageValue("make a successful purchase"));
        EventCenter.Instance.Trigger(GameEventName.SUCC_BUY, purchaseEvent.purchasedProduct.definition.id, m_Data);

        ReportBI(id, id, 0, product.amount, m_IsoCurrencyCode, "", "paid", "");

        //用户付费打点
        var eventValues = new Dictionary<string, string>
        {
            {"af_currency", m_IsoCurrencyCode },
            {"af_revenue",  product.amount.ToString(System.Globalization.CultureInfo.InvariantCulture)},
            {"customer_user_id", GameDataMgr.Instance.Uid.ToString() },
        };

        NativeInteraction.Instance.AFUploadData("af_purchase", eventValues);

        //新用户付费打点，如果当前用户付费的时间和激活时间小于24小时
        //long activeTimeTick = GameDataMgr.Instance.ActiveTimeTick;
        //DateTime activeTime = new DateTime(activeTimeTick);
        //TimeSpan span = DateTime.Now - activeTime;
        //if (span.TotalHours < 24)
        //    NativeInteraction.Instance.AFUploadData("af_new_purchase", eventValues);

        // 关闭Loading
        //UIUtility.HidePanel(Game.UI.IAPLoadingPanel.IAPLoadingPanelView.PANEL_KEY);

        ResetData();
        return PurchaseProcessingResult.Complete;
    }

    public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
    {
        LogManager.LogWarning($"购买失败，{product.appleOriginalTransactionID}-{product.transactionID}！！", "Purchase", "OnPurchaseFailed");
        // 关闭Loading
        //UIUtility.HidePanel(Game.UI.IAPLoadingPanel.IAPLoadingPanelView.PANEL_KEY);
        EventCenter.Instance.Trigger(GameEventName.BUY_FAILED, product.definition.id);
        UIUtility.ShowToast(BaseDataMgr.Instance.GetLanguageValue("purchase failed!"));
        string id = product.definition.storeSpecificId;
        ReportBI(id, id, 0, m_Cfg[product.definition.id].amount, m_IsoCurrencyCode, "", "paid_err", "");
    }

    public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
        m_Controller = controller;
        m_Extensions = extensions;

        // 修改产品价格（根据当前区域的货币）
        foreach (var product in m_Cfg.products)
        {
            foreach (var product2 in m_Controller.products.all)
            {
                if (product.id.Equals(product2.definition.id))
                    product.amount = (float)product2.metadata.localizedPrice;
            }
        }
        LogManager.Log($"初始化IAP成功，现在可以进行购买了！！", "Purchase");
        foreach (var product2 in m_Controller.products.all)
        {
            if (m_IsoCurrencyCode != product2.metadata.isoCurrencyCode)
                m_IsoCurrencyCode = product2.metadata.isoCurrencyCode;
            LogManager.Log($"商品ID: {product2.definition.id} | 类型: {product2.definition.type} | 货币代码: {product2.metadata.isoCurrencyCode} | 价格: {product2.metadata.localizedPrice} | 价格字符串: {product2.metadata.localizedPriceString} | 标题: {product2.metadata.localizedTitle} | 描述: {product2.metadata.localizedDescription}", "Purchase");
        }
    }

    #endregion

    #region 购买相关API

    /// <summary>恢复交易</summary>
    public void RestoreTransactions()
    {
        if (m_Extensions == null)
        {
            LogManager.LogWarning($"IAP扩展控制器为空，无法恢复交易！！");
            UIUtility.ShowToast(BaseDataMgr.Instance.GetLanguageValue("Please ensure that your Settings allow in-app purchases!!"));
            return;
        }
        m_Extensions.GetExtension<IAppleExtensions>().RestoreTransactions((isSucc, error) =>
        {
            if (isSucc)
            {
                LogManager.Log($"恢复交易成功！！");
                GameDataMgr.Instance.IsResotred = true;
            }
            else
            {
                LogManager.LogWarning($"恢复交易失败，{error}！！");
            }
        });
    }

    /// <summary>购买</summary>
    public override void Buy(string productId, object data)
    {
        if (m_Controller == null || m_Extensions == null || m_Controller.products.WithID(productId) == null)
        {
            LogManager.LogWarning($"IAP为初始化，无法购买！！");
            UIUtility.ShowToast(BaseDataMgr.Instance.GetLanguageValue("Please ensure that your Settings allow in-app purchases!!"));
            EventCenter.Instance.Trigger(GameEventName.BUY_FAILED, productId);
            return;
        }
        base.Buy(productId, data);

        ReportBI(productId, productId, 0, m_Cfg[productId].amount, m_IsoCurrencyCode, "", "order", "");
        m_Controller.InitiatePurchase(productId);

        // 打开Loading
        //UIUtility.DisplayPanel(Game.UI.IAPLoadingPanel.IAPLoadingPanelView.PANEL_KEY, "UI/IAPLoadingPanel/Prefabs/IAPLoadingPanel");
        EventCenter.Instance.Trigger(GameEventName.REQUEST_BUY, productId);
    }

    #endregion
}
